<template>
  <el-dialog
    v-model="visible"
    title="忘记密码"
    width="480px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-steps :active="resetStep" align-center finish-status="success" class="reset-steps">
      <el-step title="验证身份" />
      <el-step title="验证码" />
      <el-step title="重置密码" />
    </el-steps>

    <!-- 步骤1：验证身份 -->
    <el-form
      v-if="resetStep === 0"
      ref="identityFormRef"
      :model="resetForm"
      :rules="identityRules"
      label-width="90px"
      class="reset-form"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="resetForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="邮箱/手机" prop="contact">
        <el-input
          v-model="resetForm.contact"
          placeholder="请输入注册时的邮箱或手机号"
          prefix-icon="Message"
        />
      </el-form-item>
      <el-form-item>
        <div class="form-tips">
          <el-icon><InfoFilled /></el-icon>
          <span>我们将向您的邮箱或手机发送验证码</span>
        </div>
      </el-form-item>
    </el-form>

    <!-- 步骤2：输入验证码 -->
    <el-form
      v-if="resetStep === 1"
      ref="codeFormRef"
      :model="resetForm"
      :rules="codeRules"
      label-width="90px"
      class="reset-form"
    >
      <el-form-item label="验证码" prop="code">
        <div class="code-input-wrapper">
          <el-input
            v-model="resetForm.code"
            placeholder="请输入6位验证码"
            maxlength="6"
            prefix-icon="Lock"
          />
          <el-button
            :disabled="countdown > 0"
            @click="sendVerificationCode"
            type="primary"
            plain
          >
            {{ countdown > 0 ? `${countdown}秒后重发` : '重新发送' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="form-tips success">
          <el-icon><SuccessFilled /></el-icon>
          <span>验证码已发送至 {{ maskContact(resetForm.contact) }}</span>
        </div>
      </el-form-item>
    </el-form>

    <!-- 步骤3：重置密码 -->
    <el-form
      v-if="resetStep === 2"
      ref="passwordFormRef"
      :model="resetForm"
      :rules="passwordRules"
      label-width="90px"
      class="reset-form"
    >
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="resetForm.newPassword"
          type="password"
          placeholder="请输入新密码（6-20位）"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="resetForm.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item>
        <div class="password-strength">
          <span>密码强度：</span>
          <div class="strength-bar">
            <div
              class="strength-fill"
              :class="passwordStrength.level"
              :style="{ width: passwordStrength.width }"
            ></div>
          </div>
          <span class="strength-text" :class="passwordStrength.level">
            {{ passwordStrength.text }}
          </span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="resetStep > 0" @click="handlePrev">上一步</el-button>
        <el-button
          type="primary"
          :loading="resetLoading"
          @click="handleNext"
        >
          {{ resetStep === 2 ? '完成重置' : '下一步' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, SuccessFilled } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const resetStep = ref(0)
const resetLoading = ref(false)
const countdown = ref(0)
let countdownTimer = null

const identityFormRef = ref()
const codeFormRef = ref()
const passwordFormRef = ref()

const resetForm = reactive({
  username: '',
  contact: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const identityRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入邮箱或手机号', trigger: 'blur' },
    {
      pattern: /^(1[3-9]\d{9}|[\w.-]+@[\w.-]+\.\w+)$/,
      message: '请输入有效的邮箱或手机号',
      trigger: 'blur'
    }
  ]
}

const codeRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位', trigger: 'blur' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const passwordStrength = computed(() => {
  const pwd = resetForm.newPassword
  if (!pwd) return { level: 'weak', text: '弱', width: '0%' }

  let strength = 0
  if (pwd.length >= 8) strength += 1
  if (pwd.length >= 12) strength += 1
  if (/\d/.test(pwd)) strength += 1
  if (/[a-z]/.test(pwd)) strength += 1
  if (/[A-Z]/.test(pwd)) strength += 1
  if (/[!@#$%^&*(),.?":{}|<>]/.test(pwd)) strength += 1

  if (strength <= 2) {
    return { level: 'weak', text: '弱', width: '33%' }
  } else if (strength <= 4) {
    return { level: 'medium', text: '中', width: '66%' }
  } else {
    return { level: 'strong', text: '强', width: '100%' }
  }
})

const maskContact = (contact) => {
  if (!contact) return ''
  if (contact.includes('@')) {
    const [name, domain] = contact.split('@')
    return name.substring(0, 2) + '***@' + domain
  } else {
    return contact.substring(0, 3) + '****' + contact.substring(7)
  }
}

const sendVerificationCode = async () => {
  try {
    ElMessage.success('验证码已发送，请查收')
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
        countdownTimer = null
      }
    }, 1000)
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  }
}

const handleNext = async () => {
  try {
    if (resetStep.value === 0) {
      await identityFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        resetStep.value = 1
        sendVerificationCode()
      }, 500)
    } else if (resetStep.value === 1) {
      await codeFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        if (resetForm.code === '123456') {
          resetStep.value = 2
          ElMessage.success('验证码正确')
        } else {
          ElMessage.error('验证码错误，测试验证码为：123456')
        }
      }, 500)
    } else if (resetStep.value === 2) {
      await passwordFormRef.value.validate()
      resetLoading.value = true
      setTimeout(() => {
        resetLoading.value = false
        ElMessage.success('密码重置成功！请使用新密码登录')
        visible.value = false
        emit('success')
        if (countdownTimer) {
          clearInterval(countdownTimer)
          countdownTimer = null
          countdown.value = 0
        }
      }, 800)
    }
  } catch (error) {
    console.error('操作失败:', error)
  }
}

const handlePrev = () => {
  resetStep.value--
}

const handleCancel = () => {
  visible.value = false
}

const handleClose = () => {
  resetStep.value = 0
  Object.assign(resetForm, {
    username: '',
    contact: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  })
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
    countdown.value = 0
  }
}

watch(visible, (val) => {
  if (!val) {
    handleClose()
  }
})
</script>

<style scoped>
.reset-steps {
  margin-bottom: 30px;
}

.reset-form {
  margin-top: 30px;
  padding: 0 20px;
}

.form-tips {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
  border-radius: 6px;
  color: #409eff;
  font-size: 13px;
}

.form-tips.success {
  background: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.3);
  color: #67c23a;
}

.code-input-wrapper {
  display: flex;
  gap: 10px;
}

.code-input-wrapper .el-input {
  flex: 1;
}

.code-input-wrapper .el-button {
  min-width: 110px;
}

.password-strength {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
  color: #606266;
}

.strength-bar {
  flex: 1;
  height: 6px;
  background: #e4e7ed;
  border-radius: 3px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  border-radius: 3px;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: linear-gradient(90deg, #f56c6c, #ff8080);
}

.strength-fill.medium {
  background: linear-gradient(90deg, #e6a23c, #f0b960);
}

.strength-fill.strong {
  background: linear-gradient(90deg, #67c23a, #85ce61);
}

.strength-text {
  min-width: 30px;
  font-weight: 600;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.medium {
  color: #e6a23c;
}

.strength-text.strong {
  color: #67c23a;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

